package com.caifu.service.impl;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.caifu.bean.ResultUtil;
import com.caifu.mapper.*;
import com.caifu.pojo.*;
import com.caifu.util.AesMyUtil;
import com.caifu.util.Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caifu.bean.Result;
import com.caifu.service.SysUserService;

import javax.annotation.Resource;

/**
 * <p>
 * 用户表 用户表 服务实现类
 * </p>
 *
 * @author Lyf
 * @since 2020-07-07
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper userMapper;
    @Resource
    private SysUserMenuMapper userMenuMapper;
    @Resource
    private SysOrganizationMapper orgMapper;
    @Resource
    private SysUserDataAuthMapper daMapper;
    @Resource
    private SysLogMapper logMapper;
    @Resource
    private SysLoginErrorMapper errorMapper;
    @Resource
    private SysUserRoleMapper userRoleMapper;
    @Resource
    private SysWechatUserMapper wechatUserMapper;

    @Override
    @Transactional
    public SysUser getUserByLoginName(String loginName, String postType) throws Exception{
        try {
            return userMapper.selectOne(new QueryWrapper<SysUser>().eq("login_name",loginName).eq("status","1").eq("post_type",postType));
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("获取用户信息失败！");
        }
    }

    @Override
    public SysUser getUserByLoginName(String loginName) throws Exception {
        try {
            return userMapper.selectOne(new QueryWrapper<SysUser>().eq("login_name",loginName).eq("status","1"));
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("获取用户信息失败！");
        }
    }

    @Override
    @Transactional
    public IPage<Map<String,Object>> getUserList(int currentPage, int pageSize, String loginName, String userName, String phone, String postType)throws Exception {
        try {
            Page<SysUser> page = new Page<>(currentPage,pageSize);
            IPage<Map<String,Object>> pageList;
            QueryWrapper<SysUser> qw = new QueryWrapper();
            qw.ne("status","9");
            if(StringUtils.isNotBlank(userName)){
                qw.like("USER_NAME",userName);
            }
            if(StringUtils.isNotBlank(loginName)){
                qw.like("LOGIN_NAME",loginName);
            }
            if(StringUtils.isNotBlank(phone)){
                qw.like("PHONE",phone);
            }
            //postType必填 1-系统管理员 2-供餐机构管理员
            if(StringUtils.isNotBlank(postType)){
                qw.like("POST_TYPE",postType);
            }else{
                qw.like("POST_TYPE","000");
            }
            qw.orderByDesc("user_no");
            pageList = userMapper.selectMapsPage(page,qw);

            //将所属机构，状态转成中文
            List<Map<String,Object>> list = pageList.getRecords();
            for (Map<String, Object> map : list) {
            	String orgName="";
				String orgStr = (String) map.get("ORG_ID");
				if(StringUtils.isNotBlank(orgStr)) {
                    String[] orgArr = orgStr.substring(0, orgStr.length()).split(",");
                    for (String string : orgArr) {
                        SysOrganization tmpOrg = orgMapper.selectOne(new QueryWrapper<SysOrganization>().eq("state", "1").eq("ORG_Id", string));
                        if (tmpOrg != null) {
                            orgName = orgName + tmpOrg.getOrgName() + ",";
                        }
                    }
                    if(StringUtils.isNotBlank(orgName)) {
                        orgName=orgName.substring(0,orgName.length()-1);
                    }
				}

				map.put("ORG_NAME", orgName);
				
				String status = (String) map.get("STATUS");
				String statusName = ("1".equals(status)?"开通":"停用");
				map.put("STATUS_NAME", statusName);
				
			}
            return pageList;
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("获取用户信息失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLoginTime(String loginName) throws Exception {
        try{
            UpdateWrapper<SysUser> uw = new UpdateWrapper<>();
            uw.lambda().set(SysUser::getLoginTime,new Date()).eq(SysUser::getLoginName,loginName);
            userMapper.update(null,uw);
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("更新最后登录时间失败！");
        }
    }

    @Override
    @Transactional
    public int getCountByLoginName(String loginName, String userNo) throws Exception {
        try {
            QueryWrapper<SysUser> qw = new QueryWrapper<SysUser>();
            qw.eq("login_name",loginName);
            if(StringUtils.isNotBlank(userNo)){
              qw.ne("user_no",userNo);
            }
            qw.ne("status", "9");
            return userMapper.selectCount(qw);
        }catch (Exception e){
            e.printStackTrace();
            throw new Exception("获取用户信息失败！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setUserMenu(int userNo, String menus) throws Exception {
        try {
            userMenuMapper.delete(new UpdateWrapper<SysUserMenu>().eq("user_no",userNo));
            if (StringUtils.isNotBlank(menus)) {
                String[] menuArr = menus.split(",");
                if(menuArr != null && menuArr.length > 0){
                    for(String s : menuArr){
                        SysUserMenu sum = new SysUserMenu();
                        sum.setUserNo(userNo);
                        sum.setMenuNo(Integer.parseInt(s));
                        userMenuMapper.insert(sum);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("配置用户菜单权限失败！");
        }
    }

    @Transactional
	@Override
	public Result<Object> setUserAuth(int userNo, String orgStr, int tellerNo) throws Exception {
		Result<Object> rst = new Result<>();
        SysUser user = new SysUser();
        SysUser tellerUser = new SysUser();
		try {
            user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no",userNo));
            if(user==null){
                throw new Exception("在SysUser表中找不到用户信息");
            }
            tellerUser = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no",tellerNo));
            if(tellerUser==null){
                throw new Exception("在SysUser表中找不到用户信息");
            }
			//清除用户数据权限
			daMapper.delete(new UpdateWrapper<SysUserDataAuth>().eq("USER_NO", userNo));
			
			if(StringUtils.isNotBlank(orgStr)) {
				String[] orgArr = orgStr.split(",");
				for (String string : orgArr) {
					
					List<Map<String,Object>> ancestorList = orgMapper.getAncestorOrganization(string);
					for (Map<String, Object> map : ancestorList) {
						String tmpOrgId = (long)map.get("orgId")+"";

						SysUserDataAuth da = daMapper.selectOne(new QueryWrapper<SysUserDataAuth>().eq("USER_NO", userNo).eq("org_id", tmpOrgId));
						if(da==null&&!"10".equals(tmpOrgId)) {
							SysOrganization org=orgMapper.selectOne( new QueryWrapper<SysOrganization>().eq("state", "1").eq("org_id", tmpOrgId));
							String type=(string.equals(tmpOrgId)?"1":"0");									
							da = new SysUserDataAuth();
							da.setUserNo((long)userNo);
							da.setOrgId(org.getOrgId());
							da.setOrgLevel(org.getOrgLevel());
							da.setParentOrgId(org.getParentOrgId());
							da.setType(type);
							da.setCreateBy((long)tellerNo);
							da.setCreateTime(new Date());
							daMapper.insert(da);
							
						}
					}
				}
			}	

            //日志记录  sys 组织架构模块  sys-204 操作员数据权限赋权
            SysLog log = new SysLog(userNo, "1","sys", "sys-204", "1", tellerUser.getLoginName()+"对"+user.getLoginName()+"设置数据权限成功！", new Date());
            return ResultUtil.retLog(200,"设置数据权限成功！",log);
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //日志记录  sys 组织架构模块  sys-204 操作员数据权限赋权
            SysLog log = new SysLog(userNo, "1","sys", "sys-204", "9", tellerUser.getLoginName()+"对"+user.getLoginName()+"设置数据权限失败！", new Date());
            return ResultUtil.retLog(201,"设置数据权限失败！",log);
		}
		
	}

    @Override
    @Transactional
    public Result<Object> setUserApp(int userNo, String appStr, int tellerNo) throws Exception {
        Result<Object> rst = new Result<>();
        SysUser user = new SysUser();
        SysUser tellerUser = new SysUser();
        try {
            user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no",userNo));
            if(user==null){
                throw new Exception("在SysUser表中找不到用户信息");
            }
            tellerUser = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no",tellerNo));
            if(tellerUser==null){
                throw new Exception("在SysUser表中找不到用户信息");
            }
            //清除用户应用权限
            userMenuMapper.delete(new UpdateWrapper<SysUserMenu>().eq("USER_NO", userNo).ne("menu_no",1));
            //增加用户应用权限
            if(StringUtils.isNotBlank(appStr)) {
                String[] appArr = appStr.split(",");
                for (String string : appArr) {
                    SysUserMenu menu = new SysUserMenu();
                    menu.setMenuNo(Integer.parseInt(string));
                    menu.setUserNo(userNo);
                    userMenuMapper.insert(menu);
                }
            }
            //日志记录  sys 组织架构模块  sys-203 操作员开通应用
            SysLog log = new SysLog(userNo, "1","sys", "sys-203", "1", tellerUser.getLoginName()+"对"+user.getLoginName()+"开通app成功[menuArray="+appStr+"]！", new Date());
            return ResultUtil.retLog(200,"开通应用成功！",log);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            //日志记录  sys 组织架构模块  sys-203 操作员开通应用
            SysLog log = new SysLog(userNo, "1","sys", "sys-203", "9", tellerUser.getLoginName()+"对"+user.getLoginName()+"开通app失败！", new Date());
            return ResultUtil.retLog(201,"开通应用失败！",log);
        }
    }

    @Override
    @Transactional
    public void loginError(int userNo, String loginName) throws Exception {
        try {
            SysLoginError err = new SysLoginError();
            err.setUserNo(userNo);
            err.setCreateTime(new Date());
            err.setDay(Util.currentDate());
            err.setLoginName(loginName);
            errorMapper.insert(err);
            //日志记录  sys 组织架构模块  sys-205 操作员登陆
            SysLog log = new SysLog(userNo, "1","sys", "sys-205", "9", loginName+"账号或错误, 登陆失败！", new Date());
            logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Override
    @Transactional
    public void loginSuccess(int userNo, String loginName) throws Exception {
        try {
            errorMapper.delete(new QueryWrapper<SysLoginError>().eq("user_no",userNo));
            //日志记录  sys 组织架构模块  sys-205 操作员登陆
            SysLog log = new SysLog(userNo, "1","sys", "sys-205", "1", loginName+"登陆成功！", new Date());
            logMapper.insert(log);
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdate(SysUser operUser, SysUser user, boolean isNew, String authRole, String authOrg, String postType) {
        try{
            if(user.getUserNo() != null && StringUtils.isNotBlank(user.getUserNo() + "")){
                userMapper.updateById(user);
                //日志记录  sys 组织架构模块  sys-201 操作员修改
                SysLog log = new SysLog(operUser.getUserNo(), postType,"sys", "sys-201", "1", operUser.getLoginName()+"修改操作员成功[userNo="+user.getUserNo()+"]！", new Date());
                logMapper.insert(log);
            }else{
                userMapper.insert(user);
                //日志记录  sys 组织架构模块  sys-200 操作员添加
                SysLog log = new SysLog(operUser.getUserNo(), postType,"sys", "sys-200", "1", operUser.getLoginName()+"新增操作员成功[userNo="+user.getUserNo()+"]！", new Date());
                logMapper.insert(log);
            }

            //清除用户数据权限并更新授权
            int userNo = user.getUserNo();
            int tellerNo = operUser.getUserNo();
            daMapper.delete(new UpdateWrapper<SysUserDataAuth>().eq("USER_NO", userNo));
            if(StringUtils.isNotBlank(authOrg)) {
                String[] orgArr = authOrg.split("-");
                for (String string : orgArr) {
                    List<Map<String,Object>> ancestorList = orgMapper.getAncestorOrganization(string);
                    for (Map<String, Object> map : ancestorList) {
                        String tmpOrgId = (long)map.get("orgId")+"";

                        SysUserDataAuth da = daMapper.selectOne(new QueryWrapper<SysUserDataAuth>().eq("USER_NO", userNo).eq("org_id", tmpOrgId));
                        if(da==null&&!"10".equals(tmpOrgId)) {
                            SysOrganization org=orgMapper.selectOne( new QueryWrapper<SysOrganization>().eq("state", "1").eq("org_id", tmpOrgId));
                            String type=(string.equals(tmpOrgId)?"1":"0");
                            da = new SysUserDataAuth();
                            da.setUserNo((long)userNo);
                            da.setOrgId(org.getOrgId());
                            da.setOrgLevel(org.getOrgLevel());
                            da.setParentOrgId(org.getParentOrgId());
                            da.setType(type);
                            da.setCreateBy((long)tellerNo);
                            da.setCreateTime(new Date());
                            daMapper.insert(da);

                        }
                    }
                }
            }
            //清除用户角色并授权
            userRoleMapper.delete(new QueryWrapper<SysUserRole>().eq("USER_ID", userNo));
            if(StringUtils.isNotBlank(authRole)) {
                String[] roleArr = authRole.split("-");
                for (String string : roleArr) {
                    SysUserRole role = new SysUserRole();
                    role.setUserId(userNo);
                    role.setRoleId(Integer.parseInt(string));
                    role.setCreatedTime(new Date());
                    userRoleMapper.insert(role);
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void close(String userNo, String postType) {
        try {
            UpdateWrapper<SysUser> uw = new UpdateWrapper();
            uw.set("status", "0");
            uw.eq("user_no", userNo);
            userMapper.update(null, uw);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(String userNo, String postType) {
        try {
            UpdateWrapper<SysUser> uw = new UpdateWrapper();
            uw.set("status", "9");
            uw.eq("user_no", userNo);
            userMapper.update(null, uw);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public void bindSysWechatUser(String userNo) throws Exception{
        try {
            SysUser user = userMapper.selectOne(new QueryWrapper<SysUser>().eq("user_no",userNo));
            if(user==null){
                throw new Exception("在SysUser表中找不到用户信息");
            }
            SysWechatUser wechatUser = wechatUserMapper.selectOne(new QueryWrapper<SysWechatUser>().eq("phone", user.getPhone()+""));
            if(wechatUser!=null){
                wechatUser.setSysUserNo(user.getUserNo());
                wechatUserMapper.updateById(wechatUser);
            }else{
                SysWechatUser tmpWechatUser = wechatUserMapper.selectOne(new QueryWrapper<SysWechatUser>().eq("sys_user_no", user.getUserNo()));
                tmpWechatUser.setSysUserNo(0);
                wechatUserMapper.updateById(tmpWechatUser);
            }
        } catch (Exception e){
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
}
